package com.ry.common.utils;

import com.ry.model.ProductInventory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * redis工具类
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    private RedisTemplate redisTemplate;

    private static String INVENTORY_KEY = "ry:product:inventory:";

    /**
     * 避免覆盖其他项目的序列化，只在当前类实例化一个RedisTemplate
     */
    @PostConstruct
    public void init() {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        this.redisTemplate = redisTemplate;
    }

    /**
     * 移除库存缓存
     * @param productId
     */
    public void removeInventoryCache(Long productId){
        String key = INVENTORY_KEY + productId;
        redisTemplate.delete(key);
        log.info("======删除redis库存缓存->key:{}",key);
    }

    /**
     * 设置库存缓存
     * @param productInventory
     */
    public void putInventoryCache(ProductInventory productInventory){
        String key = INVENTORY_KEY + productInventory.getProductId();
        redisTemplate.opsForValue().set(key,productInventory);
        log.info("======设置redis库存缓存->key:{},inventory:{}",key,productInventory.getInventoryCnt());
    }

    /**
     * 获取库存缓存
     * @param productId
     */
    public ProductInventory getInventoryCache(Long productId){
        String key = INVENTORY_KEY + productId;
        ValueOperations<String,ProductInventory> valueOperations = redisTemplate.opsForValue();
        log.info("======获取redis库存缓存->key:{}",key);
        return valueOperations.get(key);
    }

}
